﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 图片查看器
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainViewModel vm;
        private bool isMouseDown = false;
        private Point mousePoint = new Point(0, 0);
        private TranslateTransform translateTransform = new TranslateTransform();
        private ScaleTransform scaleTransform = new ScaleTransform();
        private TransformGroup group = new TransformGroup();
        public MainWindow()
        {
            InitializeComponent();
          
            Loaded += (s, e) =>
            {
                vm = DataContext as MainViewModel;
                group.Children.Add(scaleTransform);
                group.Children.Add(translateTransform);
                image.RenderTransform = group;
                var scale = Math.Min(
                    canvas.ActualWidth / image.ActualWidth,
                    canvas.ActualHeight / image.ActualHeight);
                scaleTransform.ScaleX = scale;
                scaleTransform.ScaleY = scale;
                translateTransform.X = (canvas.ActualWidth - image.ActualWidth * scale) / 2;
            };
        }



        private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isMouseDown = true;
            mousePoint = e.GetPosition(canvas);
        }

        private void canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isMouseDown = false;
        }

        private void canvas_MouseMove(object sender, MouseEventArgs e)
        {
            var position = e.GetPosition(canvas);
            vm.X = position.X;
            vm.Y = position.Y;
            if (isMouseDown)
            {
                translateTransform.X += position.X - mousePoint.X;
                translateTransform.Y += position.Y - mousePoint.Y;
                mousePoint = position;
            }
        }

        private void canvas_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            var delta = e.Delta;
            double scale = delta * 0.001;
            var position = e.GetPosition(canvas);
            vm.X = position.X;
            vm.Y = position.Y;
            vm.D = delta;

            if (scaleTransform.ScaleX + scale < 0.1) return;

            Point inversePoint = group.Inverse.Transform(position);
            scaleTransform.ScaleX += scale;
            scaleTransform.ScaleY += scale;
            translateTransform.X = -(inversePoint.X * scaleTransform.ScaleX - position.X);
            translateTransform.Y = -(inversePoint.Y * scaleTransform.ScaleY - position.Y);
        }
    }
}